using System;
using System.Collections.Generic;
using System.Text;
using Koda.VisualStudio.Integration;
using EnvDTE;
using EnvDTE80;

namespace Koda.Commands
{
    public class CollapseAllProjectsCommand : VsCommand
    {
        private const string PhysicalFile = "{6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}";
        private const string PhysicalFolder = "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}";

        public CollapseAllProjectsCommand()
            : base("Collapse All Projects", "Solution", 1)
        {
        }

        public override void OnExecute(VsCommandEventArgs e)
        {
            Window window = e.DTE.Windows.Item(Constants.vsext_wk_SProjectWindow);
            UIHierarchy solutionExplorer = (UIHierarchy)window.Object;

            if (solutionExplorer.UIHierarchyItems.Count > 0)
            {
                e.DTE.SuppressUI = true;
                foreach (UIHierarchyItem item in solutionExplorer.UIHierarchyItems)
                {
                    this.Collapse(item, solutionExplorer);
                }
                e.DTE.SuppressUI = false;
            }
        }

        private void Collapse(UIHierarchyItem rootItem, UIHierarchy solutionExplorer)
        {
            foreach (UIHierarchyItem item in rootItem.UIHierarchyItems)
            {
                if (this.DoCollapse(item))
                {
                    this.Collapse(item, solutionExplorer);

                    if (item.UIHierarchyItems.Expanded)
                    {
                        item.UIHierarchyItems.Expanded = false;
                        if (item.UIHierarchyItems.Expanded)
                        {
                            item.Select(vsUISelectionType.vsUISelectionTypeSelect);
                            solutionExplorer.DoDefaultAction();
                        }
                    }
                }
            }
        }

        private bool DoCollapse(UIHierarchyItem item)
        {
            if (item.UIHierarchyItems.Count > 0)
            {
                if (item.Object is ProjectItem)
                {
                    ProjectItem projectItem = (ProjectItem)item.Object;
                    if (projectItem.Kind == PhysicalFile || projectItem.Kind == PhysicalFolder)
                        return false;

                    return true;
                }
                else if (item.Object is Project || item.Object is SolutionClass)
                {
                    return true;
                }
            }
            return false;
        }

    }
}